38) Write a program to convert a decimal number to hexadecimal in C++.
In this we are going to see  a program to convert decimal number to hexadecimal number in C++ Programming Language.



The Code given below can be used in TURBO C++ Compilers: -

#include <iostream.h>
#include <conio.h>
void main()
{
    clrscr();
    int num, i=0, j, y;
    char hex[100];
    cout<<"Enter a decimal number: ";
    cin>>num;
    while (num>0) 
	{
		y=num%16;
		if(y>9)
		hex[i]=y+55;
		else
		hex[i]=y+48;
        num=num/16;
        i++;
    }
    cout<<"The hexadecimal equivalent is ";
    for (j=i-1; j>=0; j--)
        cout<<hex[j];
    getch();
}


The Code given below can be used in gcc/g++ Compilers: -

#include <iostream>
using namespace std;

int main()
{
    int num, i = 0, j = 0, x, y;
    cout << "Enter a decimal number: ";
    cin >> num;
    x = num;
    while (x > 0)
    {
        x = x / 16;
        j++;
    }
    char hex[j];
    while (num > 0)
    {
        y = num % 16;
        if (y > 9)
            hex[i] = y + 55;
        else
            hex[i] = y + 48;
        num = num / 16;
        i++;
    }
    cout << "The hexadecimal equivalent is ";
    for (j = i - 1; j >= 0; j--)
        cout << hex[j];
    return 0;
}



#ENJOY CODING

Post a Comment

FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP

Previous Post Next Post